﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using QuickMAP.Code;

namespace QuickMAP.UI
{
    public partial class frmTemplateMgr : Form
    {
        public static string TemplatesDir = "D:\\Projs\\QuickMAP\\QuickMAP\\Templates";
        static string CurrentNode = "";

        private bool _modified = false;

        public frmTemplateMgr()
        {
            InitializeComponent();
        }

        private void frmTemplateMgr_Load(object sender, EventArgs e)
        {
            ArrayList list = new ArrayList();
            //获取主目录下所有模文件和文件夹
            foreach (string item in Directory.GetDirectories(TemplatesDir))
            {
                //.BAK文件夹为备份文件夹，忽略掉
                if (item.ToUpper().EndsWith(".BAK")
                    || item.ToUpper() == "模板库")
                {
                    continue;
                }
                list.Add(item);
            }
            foreach (string item in Directory.GetFiles(TemplatesDir))
            {
                list.Add(item);
            }
            list.Sort(new FileSortComparer() { SortType = 1 });

            try
            {
                treeVTemplate.Nodes.Add(new TreeNode()
                    {
                        Name = "_ROOT_",
                        Text = "模板列表",
                        Tag = ""
                    });
                this.CreateTree(treeVTemplate.Nodes["_ROOT_"], list);
                treeVTemplate.Nodes["_ROOT_"].Expand();
            }
            catch (Exception ex)
            {
                File.AppendAllText(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName + "/log.txt", ex.ToString() + "\r\n");
            }
        }

        /// <summary>
        /// 创建节点树
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="pathList"></param>
        private void CreateTree(TreeNode parentNode, ArrayList pathList)
        {
            //构建子目录菜单
            foreach (string fPath in pathList)
            {
                //子文件夹和文件列表
                ArrayList list = new ArrayList();
                if (Directory.Exists(fPath))
                {
                    //如果是文件夹，则将文件夹创建为父节点
                    DirectoryInfo dirInfo = new DirectoryInfo(fPath);
                    //换掉盘符路径的特殊字符
                    string key = dirInfo.FullName.Replace(":", "").Replace("\\", "").Replace(" ", "");
                    //创建父节点
                    TreeNode tn = new TreeNode()
                        {
                            Tag = fPath,
                            Name = key,
                            Text = Regex.Replace(dirInfo.Name, "^[0-9]+", "", RegexOptions.IgnoreCase)
                        };
                    parentNode.Nodes.Add(tn);

                    //将子文件夹和子文件路径放入列表
                    foreach (string item in Directory.GetDirectories(dirInfo.FullName))
                    {
                        list.Add(item);
                    }
                    foreach (string item in Directory.GetFiles(dirInfo.FullName))
                    {
                        list.Add(item);
                    }
                    list.Sort(new FileSortComparer() { SortType = 1 });

                    //递归创建菜单和子菜单
                    this.CreateTree(tn, list);
                }
                else if (File.Exists(fPath))
                {
                    //如果是文件，则准备创建菜单命令
                    FileInfo fileInfo = new FileInfo(fPath);
                    //文件名如果是纯数字，则忽略
                    if (new Regex("^[0-9]+$").IsMatch(fileInfo.Name))
                    {
                        continue;
                    }

                    //换掉盘符路径的特殊字符
                    string key = fileInfo.FullName.Replace(":", "").Replace("\\", "").Replace(" ", "");
                    try
                    {
                        //忽略hosturl文件
                        if (fileInfo.Name.ToLower() == Actions.HOST_URL
                            || fileInfo.Name.ToLower().EndsWith("_hlp"))
                        {
                            continue;
                        }
                        else
                        {
                            parentNode.Nodes.Add(new TreeNode()
                            {
                                Tag = fPath,
                                Name = key,
                                Text = Regex.Replace(fileInfo.Name, "^[0-9]+", "", RegexOptions.IgnoreCase)
                            });
                        }
                    }
                    catch (Exception ex1)
                    {
                        File.AppendAllText(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName + "/log.txt", ex1.ToString() + "\r\n");
                    }
                }
                else
                {
                    //非文件和文件夹，直接忽略
                    continue;
                }
            }
        }

        private void rchTxtTemplate_TextChanged(object sender, EventArgs e)
        {
            btnOK.Enabled = true;
        }

        
        private void treeVTemplate_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (File.Exists(treeVTemplate.SelectedNode.Tag.ToString()))
            {
                CurrentNode = treeVTemplate.SelectedNode.Tag.ToString();
                rchTxtTemplate.Enabled = true;
                rchTxtTemplate.Text = File.ReadAllText(treeVTemplate.SelectedNode.Tag.ToString(), Encoding.UTF8);
            }
            else
            {
                CurrentNode = "";
                rchTxtTemplate.Enabled = false;
                rchTxtTemplate.Text = "";
            }
            btnOK.Enabled = false;
            e.Node.ForeColor = Color.Red;
        }

        private void treeVTemplate_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (btnOK.Enabled==true)
            {
                DialogResult dlgResult = MessageBox.Show("是否需要放弃修改内容？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                if (dlgResult != DialogResult.Yes)
                {
                    e.Cancel = true;
                }
                else
                {
                    btnOK.Enabled = false;
                }
            }
            if (e.Cancel == false && treeVTemplate.SelectedNode!=null)
            {
                treeVTemplate.SelectedNode.ForeColor = Color.Black;
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(treeVTemplate.SelectedNode.Tag.ToString()) 
                || treeVTemplate.SelectedNode.Tag.ToString()=="")
            {
                MessageBox.Show("文件夹节点请到对应的文件夹中手动删除！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                DialogResult dlgResult = MessageBox.Show("删除选定内容后将无法恢复，是否删除选定项？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                if (dlgResult == DialogResult.Yes)
                {
                    File.Delete(treeVTemplate.SelectedNode.Tag.ToString());
                    CurrentNode = "";
                    rchTxtTemplate.Enabled = false;
                    rchTxtTemplate.Text = "";
                    btnOK.Enabled = false;
                    treeVTemplate.SelectedNode.Remove();
                    _modified = true;
                }
            }
        }

        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            File.WriteAllText(treeVTemplate.SelectedNode.Tag.ToString(), rchTxtTemplate.Text);
            btnOK.Enabled = false;
        }

        /// <summary>
        /// 关闭窗口，刷新QuickMAP菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmTemplateMgr_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_modified)
            {
                this.Hide();
                frmLoading loading = new frmLoading();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    loading.ShowDialog();
                }));
                thread.Start();
                Connect.ConnectObj.Reload();
                thread.Abort();
                loading.Close();
                loading.Dispose();
            }
        }
    }
}
